package com.eke.listener;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.jason.utils.StringUtils;

@WebListener
public class GlobalParamListener implements ServletContextListener {
		
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext sc = sce.getServletContext();
		Enumeration<String> names = sc.getInitParameterNames();
		Map<String, String> map = new HashMap<String, String>();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			map.put(name, sc.getInitParameter(name));
		}
		map.put("basePath", sc.getContextPath());
		names = sc.getInitParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			sc.setAttribute(name, getValue(map, name));
		}
	}

	private String getValue(Map<String, String> map, String name) {
		String value = map.get(name);
		// ${basePath}/static
		if (value.matches(".*\\$\\{[^}]+\\}.*")) {
			List<String> list = StringUtils.getChildStr(value, "\\$\\{[^}]+\\}");
			for (String bname : list) {
				String n1 = bname.replaceAll("[\\$\\{\\}]", "");
				value = value.replace(bname, getValue(map, n1));
			}
		}
		return value;
	}

	public void contextDestroyed(ServletContextEvent sce) {
	}

}
